package com.oracle.em12c.command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import com.google.gson.Gson;
import com.oracle.em12c.api.Element;
import com.oracle.em12c.api.VDC;
import com.oracle.em12c.api.VM;
import com.oracle.em12c.api.VMStatus;

public class DeployVM implements ApiCommand {
	private HttpsURLConnection conn;
	public DeployVM(HttpsURLConnection conn) {
		this.conn = conn;
	}
	
	public Element execute(Hashtable params) throws IOException {
		try {
			System.out.println("Execute DeployVM");
			this.conn.setDoOutput(true);
			this.conn.setDoInput(true);
			this.conn.setRequestMethod("POST");
			this.conn.setRequestProperty("Content-Type", "application/oracle.com.cloud.common.VM+json");
			this.conn.setRequestProperty("Accept", "application/oracle.com.cloud.common.VM+json");
		
			// make body
			String based_on = (String)params.get("based_on");
			String server_prefix = (String)params.get("server_prefix");
			String vnc_password = (String)params.get("vnc_password");
			String root_password = (String)params.get("root_password");
			String server_size = (String)params.get("server_size");
			
			HashMap param = new HashMap();
			Map<String, String> sub_param = new HashMap<String, String>();
			param.put("based_on", based_on);
			sub_param.put("server_prefix", server_prefix);
			sub_param.put("vnc_password", vnc_password);
			sub_param.put("root_password", root_password);
			sub_param.put("server_size", server_size);
			param.put("params", sub_param);
			
			Gson gson = new Gson();
			String json = gson.toJson(param);
			
			System.out.println("json=" + json);
			
			// Create the form content
			OutputStream out = this.conn.getOutputStream();
			Writer writer = new OutputStreamWriter(out, "UTF-8");
			writer.write(json);
			writer.close();
			out.close();
			
			if (conn.getResponseCode() != 200) {
			    throw new IOException(conn.getResponseMessage());
			  }
			
			// Buffer the result into a string
			BufferedReader rd = new BufferedReader(
			  new InputStreamReader(this.conn.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = rd.readLine()) != null) {
			    sb.append(line + "\n");
			}
			rd.close();
			
			conn.disconnect();
			System.out.println(sb.toString());
			VMStatus e = new Gson().fromJson(sb.toString(), VMStatus.class);
			return e;
			}
		catch (Exception e) {
			e.printStackTrace();
		}
		return new Element();
	}
}
